package cn.xuqiudong.blog.module.third.service.impl;

import cn.xuqiudong.blog.constant.GlobalFieldParams;
import cn.xuqiudong.blog.constant.ThirdProperties;
import cn.xuqiudong.blog.constant.ThirdUserType;
import cn.xuqiudong.blog.module.third.service.AbstractAuthService;
import cn.xuqiudong.common.base.craw.CrawlConnect;
import cn.xuqiudong.common.base.exception.CommonException;
import cn.xuqiudong.common.blog.model.BlogThirdUser;
import cn.xuqiudong.common.util.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * 描述: qq 授权 service
 * <p>
 *     https://wikinew.open.qq.com/index.html#/iwiki/876819833
 * </p>
 * @author Vic.xu
 * @since 2022-08-31 17:39
 */
@Service
public class QqAuthService extends AbstractAuthService {
    @Override
    public GlobalFieldParams.ThirdTypeEnum type() {
        return GlobalFieldParams.ThirdTypeEnum.qq;
    }

    /**
     * https://wikinew.open.qq.com/index.html#/iwiki/901251864
     * @param code code
     * @return AccessToken
     */
    @Override
    public String getAccessToken(String code) {
        ThirdProperties.ThirdAuthConfig config = config();
        CrawlConnect crawlConnect = CrawlConnect.build(config.getAccessTokenUrl()).validateTlsCertificates();
        crawlConnect.data("code", code).requestJson();

        try {
            /*
            text 的数据格式
           {"access_token":"e72e16c7e42f292c6912e7710c838347ae178b4a", "expires_in":600, "refresh_token":"xxx"}
             */
            String text = crawlConnect.getBodyText();
            logger.info("通过code[{}]获取授权码返回数据[{}]", code, text);
            return JsonUtil.jsonToObject(text, new TypeReference<Map<String, String>>() {
            }).get("access_token");
        } catch (IOException e) {
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new CommonException("获取授权码出了点问题");
        }
    }

    /**
     * 根据 accessToken 获取qq用户信息，qq需要先获取openid,  通过openid 再去获取用户
     * @param accessToken accessToken
     * @return BlogThirdUser
     */
    @Override
    public BlogThirdUser getUserInfo(String accessToken) {
        //qq\\
        try {
            String openidUrl = "https://graph.qq.com/oauth2.0/me?fmt=json";
            CrawlConnect crawlConnect = CrawlConnect.build(openidUrl).validateTlsCertificates()
                    .data("access_token", accessToken);
            String text = crawlConnect.getBodyText();
            logger.info("qq accessToken 获取openid返回信息：{}", text);
            String openid = JsonUtil.jsonToObject(text, new TypeReference<Map<String, String>>() {
            }).get("openid");
            CrawlConnect userInfoConnect = CrawlConnect.build(config().getUserUrl()).validateTlsCertificates()
                    .data("access_token", accessToken)
                    .data("openid", openid);
            String userInfoText = userInfoConnect.getBodyText();
            logger.info("accessToken[{}]和openid[{}]获取用户信息返回数据[{}]", accessToken, openid, userInfoText);
            //https://wiki.connect.qq.com/get_user_info
            /*
            {
            "ret":0,
            "msg":"",
            "nickname":"Peter",
            "figureurl":"http://qzapp.qlogo.cn/qzapp/111111/942FEA70050EEAFBD4DCE2C1FC775E56/30",
            "figureurl_1":"http://qzapp.qlogo.cn/qzapp/111111/942FEA70050EEAFBD4DCE2C1FC775E56/50",
            "figureurl_2":"http://qzapp.qlogo.cn/qzapp/111111/942FEA70050EEAFBD4DCE2C1FC775E56/100",
            "figureurl_qq_1":"http://q.qlogo.cn/qqapp/100312990/DE1931D5330620DBD07FB4A5422917B6/40",
            "figureurl_qq_2":"http://q.qlogo.cn/qqapp/100312990/DE1931D5330620DBD07FB4A5422917B6/100",
            "gender":"男"
             }
             */

            Map<String, Object> result = JsonUtil.jsonToObject(userInfoText, new TypeReference<Map<String, Object>>() {
            });
            BlogThirdUser user = new BlogThirdUser();
            String avatar = String.valueOf(result.get("figureurl_qq_2"));
            if (StringUtils.isBlank(avatar)) {
                avatar = String.valueOf(result.get("figureurl_qq_1"));
            }
            user.setAvatar(avatar);
            user.setType(ThirdUserType.qq.name());
            user.setIdentifier(openid);
            user.setNickname(String.valueOf(result.get("nickname")));

            return user;
        } catch (Exception e) {
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new CommonException("获取qq用户信息出了点问题");
        }

    }

}
